package com.example.wlf.gamerecorder.gameon;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.os.Handler;
import android.widget.Toast;

import com.example.wlf.gamerecorder.Constants;
import com.example.wlf.gamerecorder.CustomNumberPicker;
import com.example.wlf.gamerecorder.MyHandler;
import com.example.wlf.gamerecorder.R;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class SimpleGameonActivity extends AppCompatActivity {


    public static TextView lblTitle1;
    public static TextView lblTitle2;
    public static int ZERO = 0;
    private final static int COUNT = 1;
    private final static int TOTAL_TIME_24 = 24;
    public static TextView textViewTime24;
    public static TextView textViewTimeMinute;
    private static boolean hasClickedBack = false;
    public  int period = 0;
    private static int final_period = 0;
    private static String period_string;
    public  int num = TOTAL_TIME_24;
    public static Timer timer24;//24秒倒计时
    MyHandler myHandler;

    private int minValue = 1;
    private int maxValue = 4;
    private CustomNumberPicker np1;//设置节次
    private CustomNumberPicker scoreHost;//主队分数
    private CustomNumberPicker scoreGuest;//客队分数
    private int scoreHostValue = 0;//主队初始分数
    private int scoreGuestValue = 0;//客队初始分数
    private static boolean BackPressed = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_gameon);
        /**
         * 设置队名
         */
        lblTitle1=(TextView)findViewById(R.id.textView1);
        lblTitle1.setText("主队");
        lblTitle2=(TextView)findViewById(R.id.textView2);
        lblTitle2.setText("客队");
        textViewTime24=(TextView)findViewById(R.id.textViewTime24);//24秒倒计时
        final Button button_start_timer = (Button)findViewById(R.id.button_start_timer);
        textViewTimeMinute = (TextView)findViewById(R.id.textViewTimeMinute);//分钟倒计时
        button_start_timer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(period == 0){
                    showToast("请先设置比赛信息！");//
                }
                else{
                    String str = button_start_timer.getText().toString();//获取按钮字符串
                    if(str.equals("开始")){ //切换按钮文字
                        button_start_timer.setText("暂停");
                        initView();
                    }
                    else{
                        button_start_timer.setText("开始");
                        timer24.cancel();//终止线程
                    }
                }
            }
        });
        findViewById(R.id.button_start_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(timer24  != null)
                    timer24.cancel();//终止线程
                textViewTime24.setText(String.valueOf(TOTAL_TIME_24));//back to 24
                button_start_timer.setText("开始");
                //hasClickedBack = true;//has clicked back button
                num = TOTAL_TIME_24 - 1;
            }
        });

        findViewById(R.id.button_start_back_14).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(timer24  != null)
                    timer24.cancel();//终止线程
                textViewTime24.setText(String.valueOf(14));//back to 24
                button_start_timer.setText("开始");
                //hasClickedBack = true;//has clicked back button
                num = 13;// == 14 -1
            }
        });

        /**
         * 重置节时
         */
        findViewById(R.id.button_start_timer_reset).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(final_period != 0){
                    if(timer24  != null)
                        timer24.cancel();//终止线程
                    textViewTime24.setText(String.valueOf(TOTAL_TIME_24));//back to 24
                    textViewTimeMinute.setText(period_string);
                    num = TOTAL_TIME_24;//has clicked back button
                    period = final_period;
                }

            }
        });

        /**
         * 设置节次
         */
        //region Description:滚动加分
        np1 = (CustomNumberPicker) findViewById(R.id.np1);
        np1.initNumberPicker(4,1,1);
        scoreHost = (CustomNumberPicker) findViewById(R.id.score_1);
        scoreHost.initNumberPicker(200,0,0);
        scoreGuest = (CustomNumberPicker) findViewById(R.id.score_2);
        scoreGuest.initNumberPicker(200,0,0);
        setNumberPickerDividerColor(np1, Color.alpha(0x00));
        setNumberPickerDividerColor(scoreHost,0x00000000);
        setNumberPickerDividerColor(scoreGuest,0x00000000);
        //endregion
    }
    public void initView(){
        //countDown =  (TextView) findViewById(R.id.textViewTime24);
        timer24 = new Timer();
       // timerMinute = new Timer();
        //final long end = System.currentTimeMillis() + 1000*TOTAL_TIME_24;
        /**
         * 每一秒发送一次消息给handler更新UI
         * schedule(TimerTask task, long delay, long period)
         *
         */
        myHandler = new MyHandler();
        timer24.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = COUNT;
                msg.arg1 = num;
                msg.arg2 = period;
                //myHandler.sendEmptyMessage(COUNT);
                myHandler.sendMessage(msg);
                num--;
                period--;
            }
        }, 0, 1000);
        //region Description
        /**
         * schedule(TimerTask task, long delay)
         * 注意两个方法的不同，一个只执行一次，一个重复执行
         * 0秒结束在handler里实现
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    handler.sendEmptyMessage(TOTAL_TIME_24);
                    timer.cancel();
                }
            }, new Date(end));
         */

        /*
        timerMinute.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(COUNT);
            }
        }, 0, 1000);
        */
        //endregion
    }
    public void adScore(TextView lbl,int ad){
        //lbl=(TextView)findViewById(R.id.textView5);//主队分数
        String s = lbl.getText().toString();
        ad = ad + Integer.parseInt(s);//加1分
        lbl.setText(String.valueOf(ad));
    }
    public void showToast(String string){
        Toast.makeText(this,string,Toast.LENGTH_SHORT).show();
    }
    /**
     * 设置菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) { //菜单显示
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { //菜单点击
        switch(item.getItemId()){
            case R.id.setting_period_time:
                //TODO
                Intent intent = new Intent(SimpleGameonActivity.this,SettingActivity.class);
                startActivityForResult(intent,1);//打开设置活动页
                break;
            default:
        }
        return true;
    }

    @Override //回调
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch(requestCode){
            case 1:
                if(resultCode == RESULT_OK){
                    period = data.getIntExtra("int",-1);
                    final_period = period;
                    period_string  = data.getStringExtra("string");
                    //第2个参数为没有接收到参数时的默认值
                    textViewTimeMinute.setText(period_string);//更改显示
                }
                else if(resultCode == RESULT_CANCELED){
                    lblTitle1.setText(data.getStringExtra("homeTeamName"));
                    lblTitle2.setText(data.getStringExtra("guestTeamName"));
                }
                break;
            default:
        }
    }

    private void setNumberPickerDividerColor(NumberPicker number,int color) {
        Field[] pickerFields = NumberPicker.class.getDeclaredFields();
        for (Field pf : pickerFields) {
            if (pf.getName().equals("mSelectionDivider")) {
                pf.setAccessible(true);
                try {
                    //设置分割线的颜色值
                    pf.set(number, new ColorDrawable(ContextCompat.getColor(this, color)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer24 != null)
            timer24.cancel();//退出活动时，终止线程

    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(SimpleGameonActivity.this);
        dialog.setTitle("提示");
        dialog.setMessage("退出并保存比赛信息？");
        dialog.setCancelable(true);
        dialog.setPositiveButton("保存",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //BackPressed = !BackPressed;
                finish();
            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.show();
        //BackPressed = !BackPressed;//取反
        //if(!BackPressed){ //BackPressed == True时才返回
        //    super.onBackPressed();


    }
}
